package 重温_Java并发基础.code.master_worker;

import java.util.Map;
import java.util.Queue;
import java.util.Set;

/**
 * @author idea
 * @data 2020/2/15
 */
public class Worker implements Runnable {

    protected Queue<Object> workerQueue;

    protected Map<String, Object> resultMap;

    public Worker setWorkerQueue(Queue<Object> workerQueue) {
        this.workerQueue = workerQueue;
        return this;
    }

    public Worker setResultMap(Map<String, Object> resultMap) {
        this.resultMap = resultMap;
        return this;
    }

    public Object handle(Object input) throws InterruptedException {
        return input;
    }

    @Override
    public void run() {
        while (true) {
            Object input = workerQueue.poll();
            if (input == null) {
                break;
            }
            Object result = null;
            try {
                result = handle(input);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            resultMap.put(String.valueOf(result.hashCode()), result);
        }
    }



    private  void  handle_1(){
        Master master = new Master(new PlusWorker(), 10);
        for (int i = 1; i <= 100; i++) {
            master.submit(i);
        }
        int result = 0;
        master.execute();
        Map<String, Object> resultMap = master.resultMap;
        while (resultMap.size() != 0 || !master.isComplete()) {
            Set<String> keySet = resultMap.keySet();
            String key = null;
            for (String s : keySet) {
                key = s;
                break;
            }
            Integer i = null;
            if (key != null) {
                i = (Integer) resultMap.get(key);
            }
            if (i != null) {
                result += i;
            }
            if (key != null) {
                resultMap.remove(key);
            }
        }
        System.out.println(result);
    }

    //计算1+2+3+4+***+10000
    public static void main(String[] args) {
        Worker w=new Worker();
        w.handle_1();
    }


}
